package com.zkw.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;

/**
 * Created by Administrator on 2016/4/30 0030.
 * 客户端
 */
public class DiscardClient {

    public static Bootstrap b;
    public static PooledByteBufAllocator allocator = new PooledByteBufAllocator();

    static {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        b = new Bootstrap();
        b.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new DiscardClientHandler());
                    }
                });
    }

    public static Object startClient(Object obj) {
        ChannelFuture f = null;
        try {
            //start client
            f = b.connect("localhost",8999).sync();
            //将传进来的值通过下面方法直接写入到channel中传输到server
            ByteBuf byteBuf = allocator.buffer().writeBytes(((String)obj).getBytes());
            f.channel().writeAndFlush(byteBuf);
            //wait until the connection is closed
            f.channel().closeFuture().sync();
            byteBuf.clear();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //重要，将从服务器端获取到的数据传出此方法
        return f.channel().attr(AttributeKey.valueOf(CommonConstants.Attribute_key)).get();
    }
}
